<template>
  <div class="popup">
    <van-search
      v-model="params.keyword"
      show-action
      :placeholder="iptPlaceholder"
      @search="onSearch"
      @cancel="onCancel"
      @clear="onClear"
      @input="handleInput"
    />
    <HistorySearch
      v-if="blockShow==1"
      :historyKeywordList="historyKeywordList"
      :hotKeywordList="hotKeywordList"
      @handleHistoryClick="handleHistoryClick"
      @handleHotClick="handleHotClick"
    />
    <SearchList
      v-else-if="blockShow==2"
      :searchList='searchList'
      @handleSearchTipClick="handleSearchTipClick"
    />
    <Search-product
      v-else
      :filterCategory="filterCategory"
      :goodsList="goodsList"
      @handleCateMenuChange="handleCateMenuChange($event)"
      @handlePriceMenuChange="handlePriceMenuChange"
    />
  </div>
</template>

<script>
import HistorySearch from "@/components/SearchPopup/HistorySearch.vue";
import SearchProduct from "@/components/SearchPopup/SearchProduct/SearchProduct.vue";
import SearchList from "@/components/SearchPopup/SearchList.vue";
import { GetPopupData, GetSearchData, GetSearchTip } from "../request/api";
export default {
  data() {
    return {
      aaa: 1,
      //搜索框占位
      iptPlaceholder: "",
      //显示模块,1为搜索历史/热搜模块，3为显示搜索结果列表
      blockShow: 1,
      //历史记录数组
      historyKeywordList: [],
      //热门搜索
      hotKeywordList: [],
      //搜索请求的参数对象
      params: {
        //搜索框输入
        keyword: "",
        //显示页数
        page: 1,
        //一页显示个数
        size: 20,
        //排列顺序
        order: "desc",
        //类别id
        categoryId: "0",
        //排序分类id或price
        sort: "id",
      },
      //传递给SearchProduct组件显示分类数据
      filterCategory: [],
      //传递给ProductResult组件显示商品数据
      goodsList: [],
      //搜索提示数组数据
      searchList: [],
    };
  },
  components: { HistorySearch, SearchProduct, SearchList },
  created() {
    //获取搜索模块的数据
    this.getSearchData();
  },
  methods: {
    //获取搜索模块的数据
    async getSearchData() {
      //获取Popup搜索历史和热搜数据
      const res = await GetPopupData().catch((err) => console.log(err));
      // console.log(res);
      if (res.errno === 0) {
        let {
          data: { defaultKeyword, historyKeywordList, hotKeywordList },
        } = res;
        this.iptPlaceholder = defaultKeyword.keyword;
        // console.log(this.iptPlaceholder);
        //还有空字符串的。。。过滤一下
        // let index = historyKeywordList.indexOf(/日/g);//正则怎么写来着？
        // console.log(index);
        this.historyKeywordList = historyKeywordList.filter((x) => x !== "");
        this.hotKeywordList = hotKeywordList.filter((item) => item !== "");
      }
    },
    //搜索事件
    async onSearch() {
      const res = await GetSearchData({ params: this.params });
      // console.log(res);
      if (res.errno !== 0) {
        return this.$notify({ type: "danger", message: "请求搜索数据失败！" });
      }
      //搜索成功，第一步条跳转产品模块
      this.blockShow = 3;
      //保存请求数据,注意多层函数里的this可能会出现指向问题。
      let { filterCategory, goodsList } = res.data;
      //返回商品数据的数组元素对象属性名不符合Vant的DropdownMenu 下拉菜单要求绑定的固定属性名
      //修改某个数组中一个或多个对象的属性名,先进行深拷贝，再做替换：
      let arr = JSON.parse(
        JSON.stringify(filterCategory)
          .replace(/name/g, "text")
          .replace(/id/g, "value")
      );
      this.filterCategory = arr;
      // console.log(this.filterCategory);

      this.goodsList = goodsList;
      // console.log("搜索结果", this.goodsList)
    },
    //取消按钮点击事件
    onCancel() {
      // console.log(this.blockShow);
      if (this.blockShow !== 1) {
        this.blockShow = 1;
        return;
      }
      this.$router.go(-1);
      this.$store.commit("changeIsShowPopupShadow", false);
    },
    //清空按钮事件，显示搜索历史模块
    onClear() {
      this.blockShow = 1;
    },
    //分类选项改变
    handleCateMenuChange(value) {
      // console.log(value);
      this.params.categoryId = value;
      this.params.sort = "id";
      // console.log(this.params);
      this.onSearch();
    },
    //价格选项改变
    handlePriceMenuChange(value) {
      this.params.order = value;
      // console.log(this.params.order);
      this.params.sort = "price";
      this.onSearch();
    },
    //历史记录标签点击事件
    handleHistoryClick(value) {
      // console.log(value);
      this.params.keyword = value;
      this.iptPlaceholder = value;
      this.onSearch();
    },
    //热门搜索标签点击事件
    handleHotClick(value) {
      console.log(value);
      this.params.keyword = value;
      this.iptPlaceholder = value;
      this.onSearch();
    },
    //搜索框输入事件，防抖函数！
    iptDebounce(value, fn) {
      console.log(value);
      let timer;
      //这个return 的函数有执行吗？绑定了，但是input 触发并没有执行啊！
      return function () {
        console.log(1, timer);
        if (timer) {
          clearTimeout(timer);
          console.log(2, timer);
          timer = setTimeout(fn, 1000);
        } else {
          timer = setTimeout(fn, 1000);
          console.log(3, timer);
        }
      };
    },
    //搜索框输入事件发生，请求实时搜索/搜索提示，
    async handleInput(iptVal) {
      this.params.keyword = iptVal;
      //先进行判断输入框是否为空，为空则显示历史记录模块并刷新历史记录数据
      //而不是显示实时搜索提示模块
      if (iptVal == "") {
        this.blockShow = 1;
        this.getSearchData();
        return;
      }
      this.blockShow = 2;
      const res = await GetSearchTip(iptVal).catch((err) => console.log(err));
      // console.log(res);
      if (res.errno !== 0) {
        return this.$notify("请求实时搜索数据失败！");
      }
      let { data: searchList } = res;
      this.searchList = searchList;
      // console.log("发送了一次请求");
    },
    //点击实时搜索/搜索提示列表，获取子传父的点击项的值
    handleSearchTipClick(value) {
      this.params.keyword = value;
      this.onSearch();
    },
  },
};
</script>

<style lang='less' scoped>
.popup {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  //这里的right为了过渡效果，不能设置值，要在过渡enter那里设置。
  //如果是用vant内置配合transition组件的动画就不影响。
  // right: 0;
  background: #efefef;
  //后面创建的tabbar层级较高，盖住了搜索弹出层，
  //需要再给弹出层设置一个比tabbar高的层级。
  z-index: 2;
}
</style>